import { defineStore, createPinia } from 'pinia'
import { getUserMenuList } from '@/api/menu.js'
import { routes } from '@/router/index.js'
import router from '../router'
const modules = import.meta.glob("../view/**/**")
export const menuListStore = defineStore('menuListStore', {
  state: () => ({
    menuList: []
  }
  ),
  getters: {
    getMenuListRef(state) {
      return state.menuList
    },
  },
  actions: {
    queryUserMenuList(id) {
      const that = this
      return new Promise((resolve, reject) => {
        getUserMenuList(id).then(res => {
          that.menuList = res.data
          that.setRouter()
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    setRouter() {
      let data = this.menuList
      if (data !== null && data !== [] && data !== undefined) {
        const routersRef = [{
          path: '/',
          redirect: '/page/home/gaode',
          component: () => import("@/view/layout/layout.vue"),
          children: []
        }]
        data.forEach(element => {
          if (element.pagePath !== null && element.pagePath !== undefined && element.pagePath !== '') {
            const children = {
              path: element.path,
              component: modules[`../view/${element.pagePath}`]
            }
            routersRef[0].children.push(children)
          }
          element.children?.forEach(item => {
            const children = {
              path: item.path,
              component: modules[`../view/${item.pagePath}`]
            }
            routersRef[0].children.push(children)
          });
        });
        routes.forEach(item => {
          routersRef.push(item)
        })
        router.addRoute(...routersRef)
      }
    },
    clearMenuList() {
      this.menuList = []
    }
  },
  persist: {
    //这里存储默认使用的是session
    enabled: true,
    strategies: [
      {
        //key的名称
        key: 'my_menu',
        //更改默认存储，我更改为localStorage
        storage: localStorage,
        // 可以选择哪些进入local存储，这样就不用全部都进去存储了
        // 默认是全部进去存储
        paths: ['menuList']
      }
    ]
  }
})